package com.wxchat.chat.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wxchat.chat.service.WebChatSerive;
import com.wxchat.chat.util.WxChatUtils;

import net.sf.json.JSONObject;

@WebServlet("/callBack")
public class CallBackServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		第二步：通过code换取网页授权access_token
		String code = req.getParameter("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WxChatUtils.APP_ID
				+ "&secret="+WxChatUtils.APP_SECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		
		JSONObject jsonObject = WxChatUtils.getJSONObject(url);
		String access_token = jsonObject.getString("access_token");
		String openid = jsonObject.getString("openid");
		
//		拉取用户信息(需scope为 snsapi_userinfo)
		String returnUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		
		JSONObject userinfo = WxChatUtils.getJSONObject(returnUrl);
		
		/*****
		 * 1.没有账号信息，直接获取微信账号信息
		 */
//		req.setAttribute("userinfo", userinfo);
//		req.getRequestDispatcher("/weInfo.jsp").forward(req, resp);
		
		/*****
		 * 2.有账号信息，需要与账号信息进行绑定
		 */
		WebChatSerive service = new WebChatSerive();
		String sel = service.getSelect(openid);
		if(sel !=null){
			//账号和微信号已绑定
			req.setAttribute("name", sel);
			req.getRequestDispatcher("/weChatHinder.jsp").forward(req, resp);
		}else{
			//没有绑定的情况
			req.setAttribute("openid",openid);
			//没有绑定，跳转到账号登陆的页面并绑定
			req.getRequestDispatcher("/weChatEorr.jsp").forward(req, resp);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String openid = req.getParameter("openid");
		String account = req.getParameter("account");
		String apssword = req.getParameter("apssword");
		WebChatSerive service = new WebChatSerive();
		boolean up = service.getUp(openid, account, apssword);
		if(up){
			String sel = service.getSelect(openid);
			req.setAttribute("name", sel);
			req.getRequestDispatcher("/weChatHinder.jsp").forward(req, resp);
		}else{
			//账号和密码错误进行跳转
			req.setAttribute("name", "poenid="+openid+",account="+account+",apssword="+apssword);
			req.getRequestDispatcher("/weChatHinder.jsp").forward(req, resp);
		}
		
	}

	
	
}
